import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/utils/date_utils.dart';
import 'package:flutter_learn_vi/src/utils/durations_utils.dart';
import 'package:flutter_learn_vi/src/utils/string_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/16.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainHeaderTimerWidget extends StatefulWidget {
  final String startTime;

  const TrainHeaderTimerWidget({Key key, this.startTime}) : super(key: key);

  @override
  _TrainHeaderTimerWidgetState createState() => _TrainHeaderTimerWidgetState();
}

class _TrainHeaderTimerWidgetState extends State<TrainHeaderTimerWidget> {
  String _time = "";

  Timer _timer;

  DateTime _startDateTime;

  @override
  void initState() {
    super.initState();
    if (!StringUtils.isEmpty(widget.startTime)) {
      _startDateTime = ViDateUtils.getDateTime(widget.startTime);
    }
    _time = ViDateUtils.getNowDateStr(format: "HH:mm:ss");
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_startDateTime == null) {
        _time = ViDateUtils.getNowDateStr(format: "HH:mm:ss");
      } else {
        DateTime nowDateTime = DateTime.now();
        Duration duration = nowDateTime.difference(_startDateTime);
        _time = DurationUtils.format(duration);
      }

      setState(() {});
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(
          "assets/images/2.0x/time_icon.png",
          width: 18,
        ),
        SizedBox(
          width: 10,
        ),
        Text("$_time"),
      ],
    );
  }
}
